package com.zxjbyte.yiyi.framework.web.filter;

import com.zxjbyte.yiyi.framework.common.constant.Constant;
import com.zxjbyte.yiyi.framework.web.context.CryptoAlgorithm;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

/**
 *
 * 处理响应加密
 * @Author zhangxingjia
 * @Date 2025/10/31 17:43
 * @Version: 1.0
 */
public class ApiEncryptionResponseWrapper extends HttpServletResponseWrapper {

    private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    private final Object cryptoInstance;
    private final CryptoAlgorithm algorithm;
    private ServletOutputStream servletOutputStream;
    private final PrintWriter printWriter;

    public ApiEncryptionResponseWrapper(HttpServletResponse response, Object cryptoInstance, CryptoAlgorithm algorithm) throws IOException {
        super(response);
        this.cryptoInstance = cryptoInstance;
        this.algorithm = algorithm;
        printWriter = new PrintWriter(new OutputStreamWriter(outputStream, getCharacterEncoding() != null ? getCharacterEncoding() : Constant.UTF_8));
    }

    @Override
    public ServletOutputStream getOutputStream() {
        if (servletOutputStream == null) {
            servletOutputStream = new ServletOutputStream() {
                @Override
                public void write(int b) {
                    outputStream.write(b);
                }

                @Override
                @SuppressWarnings("NullableProblems")
                public void write(byte[] b) throws IOException {
                    outputStream.write(b);
                }

                @Override
                @SuppressWarnings("NullableProblems")
                public void write(byte[] b, int off, int len) {
                    outputStream.write(b, off, len);
                }

                @Override
                public boolean isReady() {
                    return true;
                }

                @Override
                public void setWriteListener(WriteListener writeListener) {
                    // 不需要实现
                }
            };
        }
        return servletOutputStream;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (servletOutputStream != null) {
            servletOutputStream.flush();
        }
        if (printWriter != null) {
            printWriter.flush();
        }
    }

    @Override
    public void reset() {
        outputStream.reset();
    }

    @Override
    public PrintWriter getWriter() {
        return printWriter;
    }

    /**
     * 获取原始响应数据
     */
    public byte[] getOriginalData() throws IOException {
        flushBuffer();
        return outputStream.toByteArray();
    }

    /**
     * 完成响应处理，进行加密并写入原始响应
     */
    public void finishResponse() throws Exception {
        // 清空 body
        HttpServletResponse response = (HttpServletResponse) this.getResponse();
        response.resetBuffer();

        // 获取 body
        byte[] body = getOriginalData();
        // 空响应检查
        if (body.length == 0) {
            return;
        }

        // 使用枚举方法进行加密
        String encryptedData = algorithm.encrypt(body, cryptoInstance);
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(encryptedData);
        response.getWriter().flush();
    }

    /**
     * 写入原始响应（加密失败时使用）
     */
    private void writeOriginalResponse(byte[] originalData) throws IOException {
        HttpServletResponse originalResponse = (HttpServletResponse) getResponse();
        originalResponse.setContentLength(originalData.length);
        originalResponse.getOutputStream().write(originalData);
        originalResponse.getOutputStream().flush();
    }
}
